package org.shj.springcloud.movie.controller;


import java.util.List;

import org.shj.springcloud.movie.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MovieController {
	
	private static final Logger log = LoggerFactory.getLogger(MovieController.class);
	
	private String userMicroServiceName = "microservice-provider-user";
	
	@Autowired
	private RestTemplate restTemplate;
	
	/* 直接知道服务地址的写法
	@GetMapping("/user/{uid}")
	public User findByUserId(@PathVariable String uid){
		return this.restTemplate.getForObject("http://localhost:9090/springcloud/" + uid, User.class);
	}*/
	
	/* 一般会通过服务发现组件去获取服务*/
	@Autowired
	private DiscoveryClient discoveryClient;
	
	@GetMapping("/user/{uid}")
	public User findById(@PathVariable String uid){
		return this.restTemplate.getForObject("http://" + userMicroServiceName + "/" + uid, User.class);
	}
	
	@GetMapping("/user-instance")
	public List<ServiceInstance> showInfo(){
		return this.discoveryClient.getInstances("microservice-provider-user");
	}
	

	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@GetMapping("/log-instance")
	public String logUserInstance(){
		ServiceInstance instance = this.loadBalancerClient.choose(userMicroServiceName);
		log.info("{}:{}:{}", instance.getServiceId(), instance.getHost(), instance.getPort());
		String rst = instance.getServiceId() + ":" + instance.getHost() + ":" + instance.getPort();
		return rst;
	}
	
	
}
